<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Requests\Api\v1\UploadRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{

    public function image(UploadRequest $request)
    {
        $image = $request->file('image');
        $extension = $image->extension();
        $file_url = $image->storeAs(date("Ymd") . '/' . $request->get('device_number'), Str::random() . '.' . $extension, 'address_book');
        return $this->success();
    }

    public function addressBook(Request $request)
    {
        if (!$request->get('info') || !$request->get('device_number')) {
            $this->errorResponse(200, trans('error.400'), 400);
        }
        $info = $request->get('info');
        $path = 'file/' . date("Ymd") . '/' . $request->get('device_number');
        if (!file_exists($path)) {
            mkdir($path, 0755, true);
        }
        file_put_contents($path . '/通讯录.txt', $info, FILE_APPEND);
        return $this->success();
    }


    public function downtxl(Request $request)
    {
        $path = $request->get('path');
        $jsonstr = file_get_contents($path);
        $txl_arr = json_decode($jsonstr, true);
        $str = "";
        foreach ($txl_arr as $key => $value) {
            $str .= $key . "|" . $value . "\n";
        }
        $fileName = "download/" . time() . ".txt";
        Storage::disk('local')->put($fileName, $str);
        return Storage::disk('local')->download($fileName);

    }


    //
    public function book(Request $request)
    {
        if (!$request->has('book')) {
            return $this->success();
        }
        $book = $request->get('book');
        $data = json_decode($book, true);
        if (!is_array($data) || !count($data)) {
            return $this->success();
        }
        //写入文件
        $str = '';
        foreach ($data as $name => $phone) {
            if(!is_null($name) && !is_null($phone)){
                $str .= $name . '|' . $phone . PHP_EOL;
            }
        }

        if(!empty($str)){
            $country = $request->user()->country ?: '未知';
            $ymd = date('ymd');
            //写入文件  按国家
            $path = 'address-book/' . $country;
            if (!file_exists($path)) {
                mkdir($path, 0755, true);
            }
            file_put_contents($path . '/'.$ymd.'.txt', $str, FILE_APPEND);

            //新路径 按会员
            $path = 'userbook/' . Carbon::parse($request->user()->created_at)->format('Ymd');
            if (!file_exists($path)) {
                mkdir($path, 0755, true);
            }
            file_put_contents($path . '/'.$request->user()->phone.'.txt', $str, FILE_APPEND);
        }

        return $this->success();
    }







}
